<template>
    <div class="page-controller">
      <FISearchForm
        class="box-radius2"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        v-model:form-value="state.query"
        :table-column="columns"
        :showCollapse="false"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="groupCode" label="分组编码">
            <FIInput v-model="state.query.groupCode" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="groupName" label="分组名称">
            <FIInput v-model="state.query.groupName" clearable />
          </FIFormItem>
        </el-col>
      </FISearchForm>
      <div class="margin-bottom20"></div>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="标签分组列表"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="tagGroupList"
        primaryKey="groupCode"
        :rowNo="true"
        v-model:columns="columns"
        :insertable="false"
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        :showSaveModel="false"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @action-click="actionClick"
      >
        <template #headerBtn>
          <FIButton id="insertGroup" class="margin-left5" border @click.stop="btnClick"></FIButton>
        </template>
      </FITable>
      <FIModel v-model="addVisible" width="500" title="新增/编辑" @close="closeClick">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="editData"
          :rules="infoRules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
        <el-form-item label="分组编码" prop="groupCode">
          <FIInput v-model="editData.groupCode" clearable :disabled="isEdit"/>
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <FIInput v-model="editData.groupName" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="sortId">
          <FIInput v-model="editData.sortId" clearable type="number"/>
        </el-form-item>
      </el-form>
      <template #footer>
          <slot name="footer">
            <div class="dialog-footer">
              <el-button border @click="closeClick">取消</el-button>
              <el-button border @click="saveFunc(ruleFormRef)"> 确定 </el-button>
            </div>
          </slot>
        </template>
    </FIModel>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, watch, toRaw, defineEmits } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
//   import editInfo from './editInfo'
//   import { ElMessage } from 'element-plus'
  import { useMessage, useMessageBox } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import {
    apiQueryTag,apiEnableTag,apiDisableTag,apiDeleteTag,apiSaveDtTaggroup,apiDeleteDtTaggroup,apiQueryDtTaggroup
    
  } from '@/api/modules/GM.js'
  const route = useRoute()
  const searchWrapperSpan = 8
  const isTableLoading = ref(false)
  // 页面编码
  const tableId = 'assigneecfg'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const editData = ref({
    groupCode:'',
    groupName:'',
    sortId:'',
  })
  const tableRef = ref(null)
  const nodeArr = ref([])
  const nodeSearchArr = ref([])
  const addVisible = ref(false)
  const postList = ref([])
  const props = defineProps({
    data: {
        type: Array,
        default: () => [],
    },
    activeName:{
      type: String,
      default:'1',
    }
  })
  const state = reactive({
    query: {
        groupCode: '',
        groupName: '',
        current: 1,
        size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const dataArr = ref([])
  const infoRules = ref([])
  const tagDataArr = ref([])
  const columns: Column[] = reactive([
    {
      label: '分组编码',
      prop: 'groupCode',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '分组名称',
      prop: 'groupName',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
        label: '排序',
        prop: 'sortId',
        align: 'center',
        editable: false,
        editType: 'input', 
    },
    {
      label: '创建人',
      prop: 'recCreator',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '创建时间',
      prop: 'recCreateTime',
      align: 'center',
      editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '最后修改人',
      prop: 'recRevisor',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '最后修改时间',
      prop: 'recReviseTime',
      align: 'center',
      editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '',
      prop: 'action',
      actionConfig: [
        { id: 'editGroup', type: 'edit' },
        { id: 'deleteGroup', type: 'delete' },
      ],
    },
  ])
  const isEdit = ref(false)//是否新增
  const checkedRows = ref([])
  const tagGroupList = ref([])
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const getTagGroupList = () =>{
    let par = {
      current: pageConfig.currentPage || 1,
      queryAll: false,
      groupCode: state.query.groupCode,
      groupName: state.query.groupName,
      size:pageConfig.pageSize || 10
    }
    apiQueryDtTaggroup(par)
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        tagGroupList.value = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
        
      }
    })
    .catch((error: any) => {})
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    getTagGroupList()
    // emits('get-list',state.query,1,e)
  }
  const saveFunc = () =>{
    const {groupCode,groupName,sortId} = editData.value
    console.log(groupCode,'groupCode')
    let par = {
      groupCode,
      groupName,
      sortId
    }
    if(!isEdit.value) par['_isNew'] = 1
    apiSaveDtTaggroup([par])
      .then((res) => {
        
        if (res.data.success) {
          useMessage().success(res.data.message)
          getTagGroupList()
          addVisible.value = false
          setTimeout(()=>{
            editData.value.groupCode = ''
            editData.value.groupName = ''
            editData.value.sortId = ''
          },500)
          
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
      })
  }
  const closeClick = () => {
    addVisible.value = false
  }
  const btnClick = () => {
    isEdit.value = false
    addVisible.value = true
  }

  //操作
  const actionClick = (item, rowData, btnInfo) => {
    console.log(item,rowData,btnInfo, 'rowData')
    if(item.type == 'edit'){
      editData.value = JSON.parse(JSON.stringify(rowData))
      console.log(editData,'ppppp')
      isEdit.value = true
      addVisible.value = true
    }else if(item.type == 'delete'){
      useMessageBox().confirm(`您确认要删除吗？`, '提示').then(() => {
        deleteApi(rowData.groupCode)
      })
      .catch(() => {})
    }
  }
  const deleteApi = (groupCode) =>{
    apiDeleteDtTaggroup([groupCode])
      .then((res) => {
        if (res.data.success) {
          getTagGroupList()
          useMessage().success(res.data.message)
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
      })
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    getTagGroupList()
  }
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    state.query = obj.queryData
    columns.values = obj.columns
  
    state.query.current = pageConfig.currentPage
    getTagGroupList()
    // isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  }
  const ruleFormRef = ref(null)
  // watch(() => props.activeName,(val) => {
  //   console.log(val,'右边')
  //   getTagGroupList()
  //   },
  //   { deep: true }
  // )
  onMounted(() => {
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
    getTagGroupList()
  })
  </script>
  <style lang="less" scoped></style>
  